<template>
  <div class="statistics-page">
    <div class="breadcrumb">
      <router-link to="/dashboard">控制面板</router-link> &gt; 
      <span>统计分析</span>
    </div>
    
    <h1>医疗众包项目统计分析</h1>
    
    <div v-if="loading" class="loading">
      <p>加载统计数据中...</p>
    </div>
    
    <div v-else-if="error" class="error">
      <p>{{ error }}</p>
    </div>
    
    <div v-else-if="!statistics" class="no-data">
      <p>暂无统计数据</p>
    </div>
    
    <div v-else class="statistics-content">
      <!-- 概览卡片 -->
      <div class="stats-overview">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-project-diagram"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.totalProjects || 0 }}</div>
            <div class="stat-label">项目总数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <i class="fas fa-history"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.totalHistoryRecords || 0 }}</div>
            <div class="stat-label">历史记录数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon active-icon">
            <i class="fas fa-spinner"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ getActiveProjectCount() }}</div>
            <div class="stat-label">活跃项目数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon completed-icon">
            <i class="fas fa-check-circle"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ getCompletedProjectCount() }}</div>
            <div class="stat-label">已完成项目数</div>
          </div>
        </div>
      </div>
      
      <!-- 项目状态分布图表 -->
      <div class="chart-section">
        <h2>项目状态分布</h2>
        <div class="chart-container">
          <div class="pie-chart">
            <div class="pie-segment" 
                 v-for="(count, status) in activeStatusDistribution" 
                 :key="status"
                 :style="{ 
                   '--percentage': getStatusPercentage(status), 
                   '--color': getStatusColor(status),
                   '--offset': getStatusOffset(status)
                 }">
            </div>
            <div class="pie-center">
              <div class="pie-total">{{ statistics.totalProjects }}</div>
              <div class="pie-label">总项目数</div>
            </div>
          </div>
          
          <div class="chart-legend">
            <div class="legend-item" v-for="(count, status) in activeStatusDistribution" :key="status">
              <div class="legend-color" :style="{ backgroundColor: getStatusColor(status) }"></div>
              <div class="legend-text">
                <div class="legend-label">{{ getStatusLabel(status) }}</div>
                <div class="legend-value">{{ count }} ({{ Math.round((count / statistics.totalProjects) * 100) }}%)</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 历史记录类型分布 -->
      <div class="chart-section">
        <h2>历史记录操作类型分布</h2>
        <div class="bar-chart">
          <div class="bar-container" v-for="(count, type) in activeHistoryTypes" :key="type">
            <div class="bar-label">{{ getHistoryTypeLabel(type) }}</div>
            <div class="bar-value-container">
              <div class="bar-value" 
                   :style="{ 
                     width: getHistoryTypePercentage(type) + '%',
                     backgroundColor: getHistoryTypeColor(type)
                   }">
              </div>
              <span class="bar-count">{{ count }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 最近活动历史表格 -->
      <div class="recent-activity-section">
        <h2>最近项目活动</h2>
        <div class="activity-table">
          <div class="activity-table-header">
            <div class="activity-cell">ID</div>
            <div class="activity-cell">项目ID</div>
            <div class="activity-cell">操作类型</div>
            <div class="activity-cell">时间</div>
            <div class="activity-cell">详情</div>
          </div>
          
          <div class="activity-table-row" v-for="history in statistics.recentHistory" :key="history.id">
            <div class="activity-cell">#{{ history.id }}</div>
            <div class="activity-cell">
              <router-link :to="`/project/${getHistoryProjectId(history)}`">
                {{ getHistoryProjectId(history) }}
              </router-link>
            </div>
            <div class="activity-cell">
              <span class="activity-type" :class="getHistoryTypeClass(history)">
                {{ getHistoryTypeText(history) }}
              </span>
            </div>
            <div class="activity-cell">{{ formatHistoryTime(history) }}</div>
            <div class="activity-cell">{{ getHistoryDetails(history) }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Statistics',
  data() {
    return {
      loading: true,
      error: null,
      statistics: null
    }
  },
  async created() {
    try {
      this.loading = true;
      const response = await this.$store.dispatch('fetchProjectStatistics');
      
      if (response.success) {
        this.statistics = response.statistics;
        console.log('统计数据:', this.statistics);
      } else {
        this.error = '获取统计数据失败';
      }
    } catch (error) {
      this.error = error.message || '发生错误';
    } finally {
      this.loading = false;
    }
  },
  methods: {
    // 获取活跃项目数
    getActiveProjectCount() {
      return this.statistics?.statusDistribution?.ACTIVE || 0;
    },
    
    // 获取已完成项目数
    getCompletedProjectCount() {
      return this.statistics?.statusDistribution?.COMPLETED || 0;
    },
    
    // 获取项目状态标签
    getStatusLabel(status) {
      switch(status) {
        case 'ACTIVE': return '进行中';
        case 'COMPLETED': return '已完成';
        case 'DELETED': return '已删除';
        default: return status;
      }
    },
    
    // 获取项目状态颜色
    getStatusColor(status) {
      switch(status) {
        case 'ACTIVE': return '#2ecc71';
        case 'COMPLETED': return '#3498db';
        case 'DELETED': return '#e74c3c';
        default: return '#95a5a6';
      }
    },
    
    // 计算饼图百分比
    getStatusPercentage(status) {
      const count = this.statistics.statusDistribution[status] || 0;
      const total = this.statistics.totalProjects || 1;
      return (count / total) * 100;
    },
    
    // 计算饼图偏移
    getStatusOffset(status) {
      let offset = 0;
      const statuses = Object.keys(this.statistics.statusDistribution);
      const index = statuses.indexOf(status);
      
      for (let i = 0; i < index; i++) {
        offset += this.getStatusPercentage(statuses[i]);
      }
      
      return offset;
    },
    
    // 获取历史记录类型标签
    getHistoryTypeLabel(type) {
      switch(type) {
        case 'CREATE': return '创建项目';
        case 'UPDATE': return '更新项目';
        case 'COMPLETE': return '完成项目';
        case 'DELETE': return '删除项目';
        default: return type;
      }
    },
    
    // 获取历史记录类型颜色
    getHistoryTypeColor(type) {
      switch(type) {
        case 'CREATE': return '#2ecc71';
        case 'UPDATE': return '#3498db';
        case 'COMPLETE': return '#9b59b6';
        case 'DELETE': return '#e74c3c';
        default: return '#95a5a6';
      }
    },
    
    // 计算历史记录类型百分比
    getHistoryTypePercentage(type) {
      const count = this.statistics.historyTypeDistribution[type] || 0;
      const total = this.getTotalHistoryTypeCount();
      return total > 0 ? (count / total) * 100 : 0;
    },
    
    // 获取历史记录类型总数
    getTotalHistoryTypeCount() {
      if (!this.statistics?.historyTypeDistribution) return 0;
      return Object.values(this.statistics.historyTypeDistribution).reduce((a, b) => a + b, 0);
    },
    
    // 获取历史记录中的项目ID
    getHistoryProjectId(history) {
      if (history.details && Array.isArray(history.details) && history.details.length > 0) {
        return history.details[0];
      }
      return '未知';
    },
    
    // 获取历史记录操作类型文本
    getHistoryTypeText(history) {
      if (history.details && Array.isArray(history.details) && history.details.length > 1) {
        const typeCode = history.details[1];
        switch(parseInt(typeCode)) {
          case 0: return '创建';
          case 1: return '更新';
          case 2: return '完成';
          case 3: return '删除';
          default: return '未知操作';
        }
      }
      return '未知操作';
    },
    
    // 获取历史记录操作类型CSS类
    getHistoryTypeClass(history) {
      if (history.details && Array.isArray(history.details) && history.details.length > 1) {
        const typeCode = history.details[1];
        switch(parseInt(typeCode)) {
          case 0: return 'type-create';
          case 1: return 'type-update';
          case 2: return 'type-complete';
          case 3: return 'type-delete';
          default: return 'type-unknown';
        }
      }
      return 'type-unknown';
    },
    
    // 格式化历史记录时间
    formatHistoryTime(history) {
      try {
        if (history.details && Array.isArray(history.details) && history.details.length > 2) {
          const timestamp = history.details[2];
          if (timestamp) {
            const date = new Date(parseInt(timestamp) * 1000);
            return date.toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            });
          }
        }
      } catch (e) {
        console.error('时间格式化错误', e);
      }
      return '未知时间';
    },
    
    // 获取历史记录详情
    getHistoryDetails(history) {
      if (history.details && Array.isArray(history.details) && history.details.length > 3) {
        return history.details[3] || '无详情';
      }
      return '无详情';
    }
  },
  computed: {
    // 过滤出计数大于0的状态分布
    activeStatusDistribution() {
      if (!this.statistics || !this.statistics.statusDistribution) return {};
      
      const result = {};
      Object.entries(this.statistics.statusDistribution).forEach(([status, count]) => {
        if (count > 0) {
          result[status] = count;
        }
      });
      
      return result;
    },
    
    // 过滤出计数大于0的历史记录类型
    activeHistoryTypes() {
      if (!this.statistics || !this.statistics.historyTypeDistribution) return {};
      
      const result = {};
      Object.entries(this.statistics.historyTypeDistribution).forEach(([type, count]) => {
        if (count > 0) {
          result[type] = count;
        }
      });
      
      return result;
    }
  }
}
</script>

<style scoped>
.statistics-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.breadcrumb a {
  color: #3498db;
  text-decoration: none;
}

.breadcrumb a:hover {
  text-decoration: underline;
}

h1 {
  margin-bottom: 30px;
  color: #2c3e50;
  text-align: center;
  font-size: 1.8rem;
}

h2 {
  color: #2c3e50;
  font-size: 1.4rem;
  margin-bottom: 20px;
  border-left: 4px solid #3498db;
  padding-left: 10px;
}

.loading, .error, .no-data {
  text-align: center;
  padding: 50px 0;
}

.error {
  color: #e74c3c;
}

.statistics-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

/* 概览卡片样式 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.stat-card {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  padding: 20px;
  display: flex;
  align-items: center;
}

.stat-icon {
  background-color: rgba(52, 152, 219, 0.1);
  color: #3498db;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  margin-right: 15px;
}

.active-icon {
  background-color: rgba(46, 204, 113, 0.1);
  color: #2ecc71;
}

.completed-icon {
  background-color: rgba(155, 89, 182, 0.1);
  color: #9b59b6;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 1.8rem;
  font-weight: bold;
  color: #2c3e50;
  line-height: 1.2;
}

.stat-label {
  color: #7f8c8d;
  font-size: 0.9rem;
}

/* 图表部分样式 */
.chart-section {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  padding: 25px;
}

.chart-container {
  display: flex;
  align-items: center;
  gap: 40px;
}

/* 饼图样式 */
.pie-chart {
  position: relative;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: #f5f5f5;
}

.pie-segment {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: conic-gradient(
    from calc(var(--offset) * 3.6deg),
    var(--color) 0deg,
    var(--color) calc(var(--percentage) * 3.6deg),
    transparent calc(var(--percentage) * 3.6deg)
  );
}

.pie-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 120px;
  height: 120px;
  background-color: white;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.pie-total {
  font-size: 2rem;
  font-weight: bold;
  color: #2c3e50;
}

.pie-label {
  font-size: 0.8rem;
  color: #7f8c8d;
}

/* 图例样式 */
.chart-legend {
  flex: 1;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  margin-right: 12px;
}

.legend-text {
  flex: 1;
}

.legend-label {
  font-weight: 500;
  color: #2c3e50;
}

.legend-value {
  font-size: 0.9rem;
  color: #7f8c8d;
}

/* 条形图样式 */
.bar-chart {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.bar-container {
  display: flex;
  align-items: center;
}

.bar-label {
  width: 120px;
  font-size: 0.9rem;
  color: #2c3e50;
}

.bar-value-container {
  flex: 1;
  display: flex;
  align-items: center;
  height: 30px;
  background-color: #f5f5f5;
  border-radius: 15px;
  overflow: hidden;
}

.bar-value {
  height: 100%;
  border-radius: 15px;
  min-width: 30px;
}

.bar-count {
  margin-left: 10px;
  margin-right: 15px;
  font-size: 0.9rem;
  color: #7f8c8d;
}

/* 活动表格样式 */
.recent-activity-section {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  padding: 25px;
}

.activity-table {
  width: 100%;
  border-collapse: collapse;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  font-size: 0.95rem;
  margin-top: 20px;
}

.activity-table-header {
  display: flex;
  background-color: #f8f9fa;
  font-weight: bold;
  border-bottom: 2px solid #dee2e6;
}

.activity-table-row {
  display: flex;
  border-bottom: 1px solid #e9ecef;
}

.activity-table-row:last-child {
  border-bottom: none;
}

.activity-cell {
  flex: 1;
  padding: 12px 15px;
  white-space: normal;
  word-break: break-word;
  display: flex;
  align-items: center;
}

/* 各列宽度调整 */
.activity-cell:nth-child(1) {
  flex: 0.5; /* ID列更窄 */
}

.activity-cell:nth-child(2) {
  flex: 0.7; /* 项目ID列稍窄 */
}

.activity-cell:nth-child(3) {
  flex: 0.7; /* 操作类型列稍窄 */
}

.activity-cell:nth-child(5) {
  flex: 2; /* 详情列更宽 */
}

.activity-type {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: bold;
  color: white;
}

.type-create {
  background-color: #2ecc71;
}

.type-update {
  background-color: #3498db;
}

.type-complete {
  background-color: #9b59b6;
}

.type-delete {
  background-color: #e74c3c;
}

.type-unknown {
  background-color: #95a5a6;
}

@media (max-width: 768px) {
  .stats-overview {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .chart-container {
    flex-direction: column;
  }
  
  .pie-chart {
    margin: 0 auto;
  }
  
  .activity-table-header, .activity-table-row {
    font-size: 0.85rem;
  }
  
  .activity-cell {
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style> 